package com.zahb.qadx.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.model.QuestionBank;
import com.zahb.qadx.model.QuestionInfo;
import com.zahb.qadx.model.QuestionInfoBean;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.JsonUtil;
import com.zahb.qadx.util.Tips;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;

public class SelectQuestionBankActivity extends BaseActivity implements OnRefreshLoadMoreListener {

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout mRefreshLayout;

    private String mDifficultyInfo;

    private int mPage;
    private static final int PAGE_SIZE = 10;

    private QuestionBankAdapter mBankAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDifficultyInfo = getIntent().getStringExtra("difficultyInfo");
        mRefreshLayout.autoRefresh();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_select_question_bank;
    }

    @Override
    protected void initViews() {
        mUnbinder = ButterKnife.bind(this);
        mRefreshLayout.setOnRefreshLoadMoreListener(this);
        mRefreshLayout.setEnableLoadMoreWhenContentNotFull(false);

        mBankAdapter = new QuestionBankAdapter(R.layout.item_list_question_bank);
        View emptyView = View.inflate(getContext(), R.layout.empty_layout, null);
        emptyView.setVisibility(View.VISIBLE);
        mBankAdapter.setEmptyView(emptyView);
        mBankAdapter.setId(getIntent().getIntExtra("id", -1));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mBankAdapter);
        int divider = DisplayUtil.dip2px(16f);
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                if (parent.getAdapter() == null) return;
                if (parent.getChildAdapterPosition(view) == 0) {
                    outRect.set(0, 0, 0, 0);
                } else {
                    outRect.set(0, divider, 0, 0);
                }
            }
        });
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.select_question_bank;
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mPage++;
        getExamPaperQuestionLibList();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPage = 1;
        getExamPaperQuestionLibList();
    }

    private Map<String, Object> params = new HashMap<>();

    private void getExamPaperQuestionLibList() {
        params.clear();
        params.put("difficultyInfo", mDifficultyInfo);
        params.put("questionLibType", 0);
        params.put("startPage", mPage);
        params.put("pageSize", PAGE_SIZE);

        addDisposable(RetrofitService.getNetService()
                .getExamPaperQuestionLibList(JsonUtil.getRequestBody(params))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (mRefreshLayout != null && mRefreshLayout.isRefreshing())
                        mRefreshLayout.finishRefresh();
                    if (mRefreshLayout != null && mRefreshLayout.isLoading())
                        mRefreshLayout.finishLoadMore(1000);
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        if (mPage == 1) {
                            mBankAdapter.setList(response.getData().getList());
                        } else {
                            List<QuestionBank> bankList = response.getData().getList();
                            if (bankList != null && bankList.size() > 0) {
                                mBankAdapter.addData(bankList);
                            } else {
                                mPage--;
                            }
                        }
                    } else if (response.getStatusCode() != Constant.CODE_OFFLINE) {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    if (mRefreshLayout != null && mRefreshLayout.isRefreshing())
                        mRefreshLayout.finishRefresh();
                    if (mRefreshLayout != null && mRefreshLayout.isLoading())
                        mRefreshLayout.finishLoadMore(1000);
                }));
    }

    private class QuestionBankAdapter extends BaseQuickAdapter<QuestionBank, BaseViewHolder> {

        private int mId = -1;
        private int mSelectPos = -1;

        public int getId() {
            return mId;
        }

        public void setId(int id) {
            mId = id;
        }

        int getSelectPos() {
            return mSelectPos;
        }

        void setSelectPos(int selectPos) {
            mSelectPos = selectPos;
        }

        QuestionBankAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(@NotNull BaseViewHolder baseViewHolder, QuestionBank questionBank) {
            baseViewHolder.setText(R.id.tv_name, questionBank.getName());
            TextView tvSelect = baseViewHolder.getView(R.id.tv_select);
            tvSelect.setTag(R.id.tag_data, questionBank);
            tvSelect.setTag(R.id.tag_pos, baseViewHolder.getAdapterPosition());
            tvSelect.setOnClickListener(mOnClickListener);
            if (questionBank.getId() == getId()) {
                tvSelect.setText("已选");
                tvSelect.setTextColor(Color.parseColor("#FFFFFF"));
                tvSelect.setBackgroundResource(R.drawable.shape_blue_corners_18dp);
                setSelectPos(baseViewHolder.getAdapterPosition());
            } else {
                tvSelect.setText("选择");
                tvSelect.setTextColor(Color.parseColor("#4C87FF"));
                tvSelect.setBackgroundResource(R.drawable.shape_border_blue_corners_18dp);
            }
        }
    }

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            QuestionBank questionBank = (QuestionBank) v.getTag(R.id.tag_data);
            int selectPos = (int) v.getTag(R.id.tag_pos);
            int preSelectPos = mBankAdapter.getSelectPos();
            getQuestionInfoList(questionBank, selectPos, preSelectPos);
        }
    };

    private void getQuestionInfoList(QuestionBank questionBank, int selectPos, int preSelectPos) {
        showProgressDialog("请稍等...");
        addDisposable(RetrofitService.getNetService()
                .getQuestionInfoList(questionBank.getId(), mDifficultyInfo)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        mBankAdapter.setId(questionBank.getId());
                        mBankAdapter.setSelectPos(selectPos);
                        mBankAdapter.notifyItemChanged(selectPos);
                        mBankAdapter.notifyItemChanged(preSelectPos);

                        QuestionInfo questionInfo = response.getData();
                        List<QuestionInfoBean> questionInfoBeans = new ArrayList<>();

                        QuestionInfoBean questionInfoBean1 = questionInfo.get单选题();
                        questionInfoBean1.setTypeName("单选");
                        questionInfoBean1.setType(1);
                        questionInfoBeans.add(questionInfoBean1);

                        QuestionInfoBean questionInfoBean2 = questionInfo.get多选题();
                        questionInfoBean2.setTypeName("多选");
                        questionInfoBean2.setType(2);
                        questionInfoBeans.add(questionInfoBean2);

                        QuestionInfoBean questionInfoBean3 = questionInfo.get判断题();
                        questionInfoBean3.setTypeName("判断");
                        questionInfoBean3.setType(3);
                        questionInfoBeans.add(questionInfoBean3);

                        QuestionInfoBean questionInfoBean4 = questionInfo.get填空题();
                        questionInfoBean4.setTypeName("填空");
                        questionInfoBean4.setType(4);
                        questionInfoBeans.add(questionInfoBean4);

                        QuestionInfoBean questionInfoBean5 = questionInfo.get简答题();
                        questionInfoBean5.setTypeName("简答");
                        questionInfoBean5.setType(5);
                        questionInfoBeans.add(questionInfoBean5);

                        QuestionInfoBean questionInfoBean6 = questionInfo.get案例题();
                        questionInfoBean6.setTypeName("案例");
                        questionInfoBean6.setType(6);
                        questionInfoBeans.add(questionInfoBean6);

                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putParcelable("questionBank", questionBank);
                        bundle.putParcelableArrayList("questionInfoBeans", new ArrayList<>(questionInfoBeans));
                        intent.putExtras(bundle);
                        setResult(RESULT_OK, intent);
                        finish();
                    } else if (response.getStatusCode() != Constant.CODE_OFFLINE) {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    hideProgressDialog();
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }
}
